# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Codec:

    def serialize(self, root: TreeNode) -> str:
        """Encodes a tree to a single string.
        """
        list = []
        # 后序遍历
        def postorder(root):
            if root is None:
                return
            postorder(root.left)
            postorder(root.right)
            list.append(root.val)
        postorder(root)
        return ','.join(map(str, list))
        

    def deserialize(self, data: str) -> TreeNode:
        """Decodes your encoded data to tree.
        """
        if data == '':
            return None
        list = [int(x) for x in data.split(',')]

        def build(lower, upper):
            # 通过lower和upper来判断是否到达了叶子节点，如果是，则返回None
            if len(list) == 0 or list[-1] < lower or list[-1] > upper:
                return None
            val = list.pop()
            root = TreeNode(val)
            root.right = build(val, upper)
            root.left = build(lower, val)
            return root

        return build(float('-inf'), float('inf'))



# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans